# -*- coding: utf-8 -*-
"""
多城市支持模块 - 任务2.3
负责城市切换功能和城市数据管理
"""

import logging
from typing import Dict, Any, List, Optional, Set
from datetime import datetime
from enum import Enum


class CityStatus(Enum):
    """城市状态枚举"""
    PENDING = "pending"      # 待处理
    PROCESSING = "processing"  # 处理中
    COMPLETED = "completed"   # 已完成
    FAILED = "failed"        # 失败
    SKIPPED = "skipped"      # 跳过


class CityManager:
    """城市管理器"""
    
    def __init__(self):
        self.logger = logging.getLogger(__name__)
        
        # 城市配置
        self.cities = {
            '深圳': {
                'code': 'sz',
                'domain': 'sz.pupuwang.com',
                'display_name': '深圳市',
                'region': '华南',
                'timezone': 'Asia/Shanghai',
                'expected_business_types': ['餐饮', '零售', '娱乐']
            },
            '杭州': {
                'code': 'hz',
                'domain': 'hz.pupuwang.com',
                'display_name': '杭州市',
                'region': '华东',
                'timezone': 'Asia/Shanghai',
                'expected_business_types': ['餐饮', '零售', '娱乐']
            },
            '长沙': {
                'code': 'cs',
                'domain': 'cs.pupuwang.com',
                'display_name': '长沙市',
                'region': '华中',
                'timezone': 'Asia/Shanghai',
                'expected_business_types': ['餐饮', '零售', '娱乐']
            },
            '西安': {
                'code': 'xa',
                'domain': 'xa.pupuwang.com',
                'display_name': '西安市',
                'region': '西北',
                'timezone': 'Asia/Shanghai',
                'expected_business_types': ['餐饮', '零售', '娱乐']
            },
            '厦门': {
                'code': 'xm',
                'domain': 'xm.pupuwang.com',
                'display_name': '厦门市',
                'region': '华东',
                'timezone': 'Asia/Shanghai',
                'expected_business_types': ['餐饮', '零售', '娱乐']
            },
            '南宁': {
                'code': 'nn',
                'domain': 'nn.pupuwang.com',
                'display_name': '南宁市',
                'region': '华南',
                'timezone': 'Asia/Shanghai',
                'expected_business_types': ['餐饮', '零售', '娱乐']
            },
            '北京': {
                'code': 'bj',
                'domain': 'bj.pupuwang.com',
                'display_name': '北京市',
                'region': '华北',
                'timezone': 'Asia/Shanghai',
                'expected_business_types': ['餐饮', '零售', '娱乐']
            },
            '武汉': {
                'code': 'wh',
                'domain': 'wh.pupuwang.com',
                'display_name': '武汉市',
                'region': '华中',
                'timezone': 'Asia/Shanghai',
                'expected_business_types': ['餐饮', '零售', '娱乐']
            }
        }
        
        # 城市状态跟踪
        self.city_status = {}
        self.city_history = []
        self.current_city = None
        self.session_data = {}  # 会话级别的城市数据隔离
        
        # 统计信息
        self.city_stats = {}
        
        self.logger.info("城市管理器初始化完成")
    
    def get_supported_cities(self) -> List[str]:
        """获取支持的城市列表"""
        return list(self.cities.keys())
    
    def get_city_config(self, city: str) -> Optional[Dict[str, Any]]:
        """获取城市配置"""
        return self.cities.get(city)
    
    def get_city_code(self, city: str) -> str:
        """获取城市代码"""
        config = self.cities.get(city)
        return config['code'] if config else 'sz'
    
    def get_city_domain(self, city: str) -> str:
        """获取城市域名"""
        config = self.cities.get(city)
        return config['domain'] if config else 'sz.pupuwang.com'
    
    def get_city_display_name(self, city: str) -> str:
        """获取城市显示名称"""
        config = self.cities.get(city)
        return config['display_name'] if config else city
    
    def switch_city(self, city: str) -> bool:
        """切换城市"""
        try:
            if city not in self.cities:
                self.logger.error(f"不支持的城市: {city}")
                return False
            
            # 记录切换历史
            switch_record = {
                'from_city': self.current_city,
                'to_city': city,
                'switch_time': datetime.now(),
                'success': True
            }
            
            # 更新当前城市
            previous_city = self.current_city
            self.current_city = city
            
            # 初始化城市状态
            if city not in self.city_status:
                self.city_status[city] = CityStatus.PENDING
            
            # 初始化城市数据存储
            if city not in self.session_data:
                self.session_data[city] = {
                    'business_data': {},  # 按业态分类的数据
                    'total_data': [],
                    'start_time': datetime.now(),
                    'business_count': 0,
                    'page_count': 0,
                    'error_count': 0
                }
            
            # 记录历史
            self.city_history.append(switch_record)
            
            self.logger.info(f"城市切换成功: {previous_city} -> {city}")
            return True
            
        except Exception as e:
            self.logger.error(f"城市切换失败: {e}")
            # 记录失败的切换
            switch_record = {
                'from_city': self.current_city,
                'to_city': city,
                'switch_time': datetime.now(),
                'success': False,
                'error': str(e)
            }
            self.city_history.append(switch_record)
            return False
    
    def set_city_status(self, city: str, status: CityStatus):
        """设置城市状态"""
        if city in self.cities:
            self.city_status[city] = status
            self.logger.debug(f"城市状态更新: {city} -> {status.value}")
    
    def get_city_status(self, city: str) -> CityStatus:
        """获取城市状态"""
        return self.city_status.get(city, CityStatus.PENDING)
    
    def add_city_business_data(self, city: str, business_type: str, data: List[Dict[str, Any]]):
        """添加城市业态数据"""
        if city not in self.session_data:
            self.session_data[city] = {
                'business_data': {},
                'total_data': [],
                'start_time': datetime.now(),
                'business_count': 0,
                'page_count': 0,
                'error_count': 0
            }
        
        # 按业态分类存储
        if business_type not in self.session_data[city]['business_data']:
            self.session_data[city]['business_data'][business_type] = []
        
        self.session_data[city]['business_data'][business_type].extend(data)
        self.session_data[city]['total_data'].extend(data)
        
        # 更新业态计数
        if business_type not in [bt for bt_data in self.session_data[city]['business_data'].values() for bt in bt_data]:
            self.session_data[city]['business_count'] += 1
        
        self.logger.debug(f"添加 {city} - {business_type} 数据: {len(data)} 条")
    
    def get_city_data(self, city: str, business_type: str = None) -> List[Dict[str, Any]]:
        """获取城市数据"""
        if city not in self.session_data:
            return []
        
        if business_type:
            return self.session_data[city]['business_data'].get(business_type, [])
        else:
            return self.session_data[city]['total_data']
    
    def increment_city_page_count(self, city: str):
        """增加城市页面计数"""
        if city in self.session_data:
            self.session_data[city]['page_count'] += 1
    
    def increment_city_error_count(self, city: str):
        """增加城市错误计数"""
        if city in self.session_data:
            self.session_data[city]['error_count'] += 1
    
    def validate_city_data(self, city: str, data: List[Dict[str, Any]]) -> Dict[str, Any]:
        """验证城市数据"""
        try:
            config = self.cities.get(city)
            if not config:
                return {'valid': False, 'error': f'未知城市: {city}'}
            
            validation_result = {
                'valid': True,
                'total_count': len(data),
                'valid_count': 0,
                'invalid_count': 0,
                'city_accuracy': 0.0,
                'business_type_distribution': {},
                'issues': []
            }
            
            city_matches = 0
            business_type_counts = {}
            
            for item in data:
                is_valid = True
                
                # 检查城市标识准确性
                item_city = item.get('city', '').strip()
                if item_city == city or item_city == config['display_name']:
                    city_matches += 1
                elif not item_city:
                    # 如果没有城市信息，设置为当前城市
                    item['city'] = city
                    city_matches += 1
                
                # 统计业态分布
                business_type = item.get('business_type', '未知')
                business_type_counts[business_type] = business_type_counts.get(business_type, 0) + 1
                
                if is_valid:
                    validation_result['valid_count'] += 1
                else:
                    validation_result['invalid_count'] += 1
            
            # 计算城市准确性
            if len(data) > 0:
                validation_result['city_accuracy'] = city_matches / len(data) * 100
                validation_result['business_type_distribution'] = business_type_counts
            
            self.logger.info(f"{city} 城市数据验证完成: {validation_result}")
            return validation_result
            
        except Exception as e:
            self.logger.error(f"城市数据验证失败: {e}")
            return {'valid': False, 'error': str(e)}
    
    def generate_city_stats(self) -> Dict[str, Any]:
        """生成城市统计信息"""
        stats = {
            'session_summary': {
                'total_cities': len(self.session_data),
                'current_city': self.current_city,
                'switch_count': len(self.city_history),
                'session_start_time': min([data['start_time'] for data in self.session_data.values()]) if self.session_data else None
            },
            'city_details': {},
            'switch_history': self.city_history,
            'status_summary': {},
            'regional_summary': {}
        }
        
        # 城市详细统计
        for city, data in self.session_data.items():
            city_config = self.cities.get(city, {})
            stats['city_details'][city] = {
                'total_data_count': len(data['total_data']),
                'business_types_count': len(data['business_data']),
                'business_data': {bt: len(bt_data) for bt, bt_data in data['business_data'].items()},
                'page_count': data['page_count'],
                'error_count': data['error_count'],
                'start_time': data['start_time'],
                'status': self.city_status.get(city, CityStatus.PENDING).value,
                'region': city_config.get('region', '未知'),
                'city_code': city_config.get('code', '')
            }
        
        # 状态汇总
        status_counts = {}
        for status in self.city_status.values():
            status_counts[status.value] = status_counts.get(status.value, 0) + 1
        stats['status_summary'] = status_counts
        
        # 区域汇总
        regional_data = {}
        for city, data in self.session_data.items():
            city_config = self.cities.get(city, {})
            region = city_config.get('region', '未知')
            if region not in regional_data:
                regional_data[region] = {
                    'cities': [],
                    'total_data_count': 0,
                    'cities_count': 0
                }
            regional_data[region]['cities'].append(city)
            regional_data[region]['total_data_count'] += len(data['total_data'])
            regional_data[region]['cities_count'] += 1
        
        stats['regional_summary'] = regional_data
        
        return stats
    
    def reset_session(self):
        """重置会话"""
        self.city_status.clear()
        self.city_history.clear()
        self.current_city = None
        self.session_data.clear()
        self.city_stats.clear()
        self.logger.info("城市管理器会话已重置")
    
    def get_current_city(self) -> Optional[str]:
        """获取当前城市"""
        return self.current_city
    
    def is_city_completed(self, city: str) -> bool:
        """检查城市是否已完成"""
        status = self.get_city_status(city)
        return status == CityStatus.COMPLETED
    
    def get_incomplete_cities(self) -> List[str]:
        """获取未完成的城市列表"""
        incomplete = []
        for city in self.cities.keys():
            if not self.is_city_completed(city):
                incomplete.append(city)
        return incomplete
    
    def get_cities_by_region(self, region: str) -> List[str]:
        """根据区域获取城市列表"""
        cities = []
        for city, config in self.cities.items():
            if config.get('region') == region:
                cities.append(city)
        return cities
    
    def apply_city_specific_processing(self, city: str, data: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
        """应用城市特定的数据处理逻辑"""
        try:
            processed_data = []
            
            for item in data:
                processed_item = item.copy()
                
                # 确保城市标识正确
                processed_item['city'] = city
                
                # 城市特定处理
                if city == '深圳':
                    processed_item = self._process_shenzhen_data(processed_item)
                elif city == '北京':
                    processed_item = self._process_beijing_data(processed_item)
                elif city == '杭州':
                    processed_item = self._process_hangzhou_data(processed_item)
                # 其他城市可以添加特定处理逻辑
                
                processed_data.append(processed_item)
            
            self.logger.debug(f"{city} 城市特定处理完成: {len(processed_data)} 条")
            return processed_data
            
        except Exception as e:
            self.logger.error(f"城市特定处理失败: {e}")
            return data
    
    def _process_shenzhen_data(self, item: Dict[str, Any]) -> Dict[str, Any]:
        """处理深圳特定数据"""
        # 深圳可能有特殊的租金模式
        rent = item.get('acceptable_rent', '')
        if '万元' in rent:
            item['high_rent_area'] = True
        
        return item
    
    def _process_beijing_data(self, item: Dict[str, Any]) -> Dict[str, Any]:
        """处理北京特定数据"""
        # 北京可能有特殊的区域标识
        title = item.get('title', '')
        if any(district in title for district in ['朝阳', '海淀', '西城', '东城']):
            item['core_district'] = True
        
        return item
    
    def _process_hangzhou_data(self, item: Dict[str, Any]) -> Dict[str, Any]:
        """处理杭州特定数据"""
        # 杭州可能有特殊的商圈标识
        title = item.get('title', '')
        if any(area in title for area in ['西湖', '滨江', '萧山']):
            item['popular_area'] = True
        
        return item
